<template>
  <div class="social-signup-container">
    <div class="sign-btn" @click="wechatHandleClick('wechat')">
      <span class="wx-svg-container">
        <svg-icon icon-class="wechat" class="icon"/>
        WeChat
      </span>
    </div>
    <div class="sign-btn" @click="tencentHandleClick('tencent')">
      <span class="qq-svg-container">
        <svg-icon icon-class="qq" class="icon"/>
        QQ
      </span>
    </div>
    <div class="sign-btn" @click="giteeHandleClick('gitee')">
      <span class="gitee-svg-container">
        <svg-icon icon-class="gitee" class="icon"/>
        Gitee
      </span>
    </div>
    <div class="sign-btn" @click="dialogVisible = true">
      <span class="gitee-svg-container">
        <svg-icon icon-class="faceId" class="icon"/>
        FaceID
      </span>
    </div>
    <el-dialog
      title="人脸识别登录"
      :visible.sync="dialogVisible"
      width="30%">
      <face :type-boolean="false" @dialogVisibleFace="dialogVisibleFace" :key="new Date().getTime()" />
      <span slot="footer" class="dialog-footer">
  </span>
    </el-dialog>
  </div>
</template>

<script>
// import { loginQQ } from '@/api/login/login'
import { getOpenIdByAccessToken } from '@/api/login/login'
// import QC from 'qc'
import Cookies from 'js-cookie'
import Face from '@/views/profile/components/Face'

export default {
  name: 'SocialSignin',
  components: { Face },
  data() {
    return {
      newWindow: null,
      redirect: undefined,
      otherQuery: {},
      count: 0,
      dialogVisible: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      const thirdpart = localStorage.getItem('thirdpart')
      if (thirdpart != null && thirdpart.length > 0) {
        switch (thirdpart) {
          case 'wechat':
            this.wechatHandleClick()
            break
          case 'tencent':
            // QQ回调
            this.tencentCallback()
            break
          case 'gitee':
            // Gitee回调
            this.giteeCallback()
            break
          default:
            break
        }
      }
    })
  },
  methods: {
    dialogVisibleFace() {
      this.dialogVisible = false
    },
    openWindow(url, title, w, h) {
      // Fixes dual-screen position                            Most browsers       Firefox
      const dualScreenLeft =
        window.screenLeft !== undefined ? window.screenLeft : screen.left
      const dualScreenTop =
        window.screenTop !== undefined ? window.screenTop : screen.top

      const width = window.innerWidth
        ? window.innerWidth
        : document.documentElement.clientWidth
          ? document.documentElement.clientWidth
          : screen.width
      const height = window.innerHeight
        ? window.innerHeight
        : document.documentElement.clientHeight
          ? document.documentElement.clientHeight
          : screen.height

      const left = width / 2 - w / 2 + dualScreenLeft
      const top = height / 2 - h / 2 + dualScreenTop
      const newWindow = window.open(
        url,
        title,
        'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' +
        w +
        ', height=' +
        h +
        ', top=' +
        top +
        ', left=' +
        left
      )
      // Puts focus on the newWindow
      if (window.focus) {
        newWindow.focus()
      }
      localStorage.setItem('newWindow', newWindow)
      this.newWindow = newWindow
    },
    wechatHandleClick(thirdpart) {
      alert('ok')
      // this.$store.commit('SET_AUTH_TYPE', thirdpart)
      // const appid = 'xxxxx'
      // const redirect_uri = encodeURIComponent('xxx/redirect?redirect=' + window.location.origin + '/auth-redirect')
      // const url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_login#wechat_redirect'
      // openWindow(url, thirdpart, 540, 540)
    },
    // 腾讯QQ第三方登录
    tencentHandleClick(thirdpart) {
      localStorage.setItem('thirdpart', thirdpart)
      // const ths = this
      // 调用弹出窗口
      // QC.Login.showPopup({
      //   appId: '101887062',
      //   redirectURI: encodeURIComponent('https://lzys522.cn/#/login')
      // })
      const appid = '101887062'
      const redirect_uri = encodeURIComponent('https://lzys522.cn/#/login')
      const url =
        'https://graph.qq.com/oauth2.0/authorize?scope=all&response_type=token&client_id=' +
        appid +
        '&redirect_uri=' +
        redirect_uri
      // this.openWindow(url, thirdpart, 540, 540)
      // https://graph.qq.com/oauth2.0/authorize?client_id=101887062&amp;
      // response_type=token&amp;scope=all&amp;redirect_uri=https%3A%2F%2Flzys522.cn%2F%23%2Flogin
      // this.newWindow = window.open(url, 'oauth2Login_10303', 'height=525,width=585, toolbar=no, menubar=no, scrollbars=no, status=no, location=yes, resizable=yes')
      this.openWindow(url, thirdpart, 540, 540)

      const t1 = window.setInterval(() => {
        const reload = Cookies.get('reload')
        console.log(reload)
        if (reload) {
          window.clearInterval(t1)
          console.log('父窗口检查是否登录授权成功', true)
          Cookies.remove('reload')
          this.newWindow.close()
          location.reload()
        }
        this.count = this.count + 1
        if (this.count >= 120) {
          window.clearInterval(t1)
          this.newWindow.close()
          console.log('登录超时', false)
          Cookies.remove('reload')
          location.reload()
        }
        console.log('父窗口检查是否登录授权成功', false)
      }, 500)

      // 组件渲染完毕，使用QC生成QQ登录按钮
      // const t1 = window.setInterval(() => {
      //   if (QC.Login.check()) {
      //     this.newWindow.close()
      //     console.log('登录是否成功:', QC.Login.check())
      //     // 获取用户信息
      //     QC.Login.getMe((openId, accessToken) => {
      //       console.log(openId, accessToken)
      //       // alert(openId, accessToken)
      //       const data = {
      //         'access_token': accessToken,
      //         'openid': openId,
      //         'oauth_consumer_key': '101887062'
      //       }
      //       // 开始请求登录获取token
      //       ths.$store.dispatch('user/getUserInfo', data).then(() => {
      //         ths.$router.push({ path: ths.redirect || '/', query: ths.otherQuery })
      //       }).catch((error) => {
      //         console.log(error)
      //       })
      //     })
      //     window.clearInterval(t1)
      //   } else {
      //     console.log(QC.Login.check())
      //   }
      // }, 1000)

      // loginQQ().then(res => {

      // })
      // alert('ok') /index
      // const appid = '101887062'
      // // const redirect_uri = encodeURIComponent('/redirect?redirect=' + window.location.origin + '/auth-redirect')
      // const redirect_uri = encodeURIComponent('https://yangbuyi.top/qq/api/oauth2')
      // const url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&=' +  + '&redirect_uri=' + redirect_uri
      // this.openWindow(url, thirdpart, 540, 540)
      // console.log('newWindow', this.newWindow)
      // if(){

      // }
      // newWindow.close()
    },
    // 腾讯回调
    tencentCallback() {
      // 返回的access_token是放在hash里面的
      const query = window.location.hash.substring(1)
      const access_token =
        query.substring(
          query.lastIndexOf('access_token=') + 13,
          query.lastIndexOf('&')
        ) || localStorage.getItem('windowOpen')
      console.log(access_token)
      if (access_token && access_token !== '/login?redir') {
        localStorage.setItem('windowOpen', access_token)
        getOpenIdByAccessToken({ access_token: access_token }).then((res) => {
          const openid = res.openid
          if (openid) {
            const data = {
              access_token: access_token,
              openid: openid,
              oauth_consumer_key: '101887062'
            }
            // 开始请求登录获取token
            this.$store
              .dispatch('user/getUserInfo', data)
              .then(() => {
                localStorage.removeItem('windowOpen')
                this.$router.push({
                  path: this.redirect || '/',
                  query: this.otherQuery
                })
                setTimeout(() => {
                  Cookies.set('reload', true)
                }, 1000)
              })
              .catch((error) => {
                console.log(error)
              })
          }
        })
      }
    },
    // Gitee 第三方登录
    giteeHandleClick(thirdpart) {
      // 记录哪个在进行第三方登录
      localStorage.setItem('thirdpart', thirdpart)
      const client_id = '5d07816cb64f92a083c984baafb6e20aa4a95520a9758633a6f780952dd98b7d'
      // Secret 16a2b06fae9f33931f7d8e5c14b6d95d36bba534b3a486f807313d3abe32a2a1
      const redirect_uri = encodeURIComponent('https://lzys522.cn/#/login')
      const getCode = `https://gitee.com/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code`
      this.openWindow(getCode, thirdpart, 540, 540)
      const t1 = window.setInterval(() => {
        const reload = Cookies.get('reload')
        console.log(reload)
        if (reload) {
          window.clearInterval(t1)
          console.log('父窗口检查是否登录授权成功', true)
          Cookies.remove('reload')
          this.newWindow.close()
          location.reload()
        }
        this.count = this.count + 1
        if (this.count >= 120) {
          window.clearInterval(t1)
          this.newWindow.close()
          console.log('登录超时', false)
          Cookies.remove('reload')
          location.reload()
        }
        console.log('父窗口检查是否登录授权成功', false)
      }, 500)
    },
    giteeCallback() {
      const href = window.location.href
      const code = href.substring(href.indexOf('?code=') + 6, href.lastIndexOf('#'))
      // 请求gitee获取用户信息
      // 开始请求登录获取token
      if (href.indexOf('?code=') !== -1 && code) {
        console.log(code)
        this.$store
          .dispatch('user/getGiteeInfo', { code: code })
          .then(() => {
            this.$router.push({
              path: this.redirect || '/',
              query: this.otherQuery
            })
            setTimeout(() => {
              Cookies.set('reload', true)
            }, 500)
          })
          .catch((error) => {
            console.log(error)
          })
      }
    },
    // 人脸识别
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
.social-signup-container {
  margin: 20px 0;

  .sign-btn {
    display: inline-block;
    cursor: pointer;
    color: #999;
    font-size: 12px;
  }

  .icon {
    color: #fff;
    font-size: 24px;
    margin-top: 8px;
  }

  .wx-svg-container,
  .qq-svg-container,
  .gitee-svg-container {
    display: inline-block;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    padding-top: 1px;
    border-radius: 4px;
    margin-bottom: 20px;
    margin-right: 5px;
    box-shadow: silver 0px -1px 15px 2px;
  }

  .wx-svg-container {
    background-color: #24da70;
  }

  .qq-svg-container {
    background-color: #6ba2d6;
    margin-left: 50px;
  }

  .gitee-svg-container {
    margin-left: 50px;
    background-color: #ffffff;
  }
}
</style>
